import sqlHelper from "./sqlHelper";

class UserModel {

	constructor() {
		this.dbName = "LanZhengDB"
		this.model = "Users"
		if (!sqlHelper.isOpen(this.dbName)) {
			sqlHelper.openDb(this.dbName)
		}

	}

	init() {
		let sql = `CREATE TABLE "${this.model}" (
						  "id" int NOT NULL,
						  "nickname" varchar(32) NOT NULL, --昵称
						  "username" varchar(32) NOT NULL, --用户名
						  "password" varchar(128) NOT NULL, --名称
						  "role_id" int DEFAULT NULL, --用户组
						  "remark" varchar(200) DEFAULT NULL, --描述
						  "login_at" datetime, --登录时间
						  "created_at" datetime, --创建时间
						  PRIMARY KEY ("id") --主键
						);`
		sqlHelper.init(this.dbName, this.model, sql)
		
		setTimeout(_ => {
			this.select({
				id: 1
			}).then(user => {
				if (!user) {
					//写入默认数据
					this.create({
						nickname: "Engineer",
						username: "qinhai",
						password: uni.$rui.md5('888888'),
						role_id: 4,
						created_at: uni.$rui.date.formatDate()
					})
				}
			})
		}, 1000)
		

	}

	create(data) {
		return new Promise((resolve, reject) => {
			sqlHelper.getDataList(this.dbName, this.model, 1, 1, 'id', 'desc').then(res => {
				data.id = Number(res[0]?.id || 0) + 1
				sqlHelper.addTabItem(this.dbName, this.model, data).then(r => {
					resolve({
						msg: "添加成功",
						code: 0
					})
				}).catch(e => {
					reject({
						msg: e,
						code: 400
					})
				})
			}).catch(e => {
				reject({
					msg: e,
					code: 400
				})
			});
		})
	}

	getPage(page = 1, size = 10) {
		return new Promise((resolve, reject) => {
			sqlHelper.getCount(this.dbName, this.model).then(res => {

				let count = res[0].num;
				if (count == 0) {
					resolve({
						data: [],
						count,
						msg: "ok",
						code: 0
					})
					return;
				}
				let maxPage = Math.ceil(count / size);
				if (maxPage < page) return false;
				sqlHelper.getDataList(this.dbName, this.model, page, size, 'id', 'asc').then(
					data => {
						resolve({
							data,
							count,
							msg: "ok",
							code: 0
						})
					})
			}).catch(e => {
				reject({
					msg: e,
					code: 400
				})
			});
		})
	}

	del(where = {}) {
		return sqlHelper.delData(this.dbName, this.model, where)
	}

	edit(data, field, value) {
		return sqlHelper.updateSQL(this.dbName, this.model, data, field, value)
	}

	select(where = {}, pk = 'id', order = 'desc') {
		return new Promise((resolve, reject) => {
			sqlHelper.selectDataList(this.dbName, this.model, where, pk, order).then(res => {
				resolve(res[0] || "")
			}).catch(err => {
				reject(err)
			})
		})
	}


}

export default UserModel